<!--
 * @Description: 
 * @Author: @yangwenshan
 * @since: 2021-05-13 15:36:56
 * @LastAuthor: @yangwenshan
 * @lastTime: 2021-05-19 16:57:48
-->
<template>
  <a-drawer title="视频详情" width="35%" placement="right" :visible="visible" @close="onClose">
    <a-spin tip="数据加载中" :spinning="loading">
      <a-form
        :form="form"
        @submit="handleSubmit"
        layout="horizontal"
        :labelCol="{ span: 3 }"
        :wrapperCol="{ span: 21 }"
      >
        <a-form-item label="视频封面">
          <div class="clearfix">
            <a-upload
              list-type="picture-card"
              :file-list="fileList1"
              accept=".jpg,.png,.jpeg,.PNG,.JPG,.JPEG"
              :before-upload="(e) => beforeUpload(e, 1)"
              :remove="(e) => handleRemove(e, 1)"
              v-decorator="[
                'poster',
                {
                  rules: [
                    {
                      required: true,
                      message: '请上传封面',
                    },
                  ],
                },
              ]"
            >
              <div v-if="fileList1.length < 1">
                <a-icon type="plus" />
                <div class="ant-upload-text">上传</div>
              </div>
            </a-upload>
          </div>
        </a-form-item>
        <a-form-item label="视频">
          <div class="clearfix">
            <a-upload
              list-type="picture-card"
              :file-list="fileList2"
              accept=".mp4"
              :before-upload="(e) => beforeUpload(e, 2)"
              :remove="(e) => handleRemove(e, 2)"
              v-decorator="[
                'video_url',
                {
                  rules: [
                    {
                      required: true,
                      message: '请上传视频',
                    },
                  ],
                },
              ]"
            >
              <div v-if="fileList2.length < 1">
                <a-icon type="plus" />
                <div class="ant-upload-text">上传</div>
              </div>
            </a-upload>
          </div>
        </a-form-item>
        <a-form-item label="题目分类">
          <a-select
            show-search
            v-decorator="[
              'type',
              {
                initialValue: data.type,
                rules: [{ required: true, message: '请输入题目分类' }],
              },
            ]"
            placeholder="请搜索题目分类"
            style="width: 100%"
            :default-active-first-option="false"
            :show-arrow="false"
            :filter-option="false"
            :not-found-content="fetching ? undefined : null"
            @search="handleSearchType"
            @change="handleChange"
          >
            <a-spin v-if="fetching" slot="notFoundContent" size="small" />
            <a-select-option v-for="item in typeList" :key="item.id">
              {{ item.name }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="标题">
          <a-input
            placeholder="请输入标题"
            v-decorator="['name', { initialValue: data.name, rules: [{ required: true, message: '请输入标题' }] }]"
          />
        </a-form-item>
        <a-form-item label="描述">
          <a-textarea
            placeholder="请输入描述"
            :auto-size="{ minRows: 6, maxRows: 10 }"
            v-decorator="['remark', { initialValue: data.remark, rules: [{ required: true, message: '请输入描述' }] }]"
          />
        </a-form-item>
        <a-form-item :wrapper-col="{ span: 12, offset: 3 }" :loading="confirmLoading">
          <a-button type="primary" html-type="submit">
            {{ mode === 'edit' ? '保存' : '新增' }}
          </a-button>
        </a-form-item>
      </a-form>
    </a-spin>
  </a-drawer>
</template>
<script>
import { addVideo, updateVideo } from '@/api/video'
import { getTypeList } from '@/api/questionType'
import request from '@/utils/request'
export default {
  data() {
    return {
      data: {},
      visible: false,
      form: this.$form.createForm(this),
      loading: false,
      fetching: false,
      mode: 'add',
      confirmLoading: false,
      fileList1: [],
      fileList2: [],
      typeList: [],
    }
  },
  methods: {
    showDrawer(record = {}) {
      this.visible = true
      this.searchTypeRequest()
      if (record.id) {
        this.data = Object.assign({}, record)
        this.fileList1 = [
          {
            uid: 1,
            name: `image_1`,
            status: 'done',
            url: record.poster_url,
          },
        ]
        this.fileList2 = [
          {
            uid: 1,
            name: `image_1`,
            status: 'done',
            url: record.video_url,
          },
        ]
        this.mode = 'edit'
        this.data.type = record.type?.id
      } else {
        this.data = {}
        this.fileList = []
        this.mode = 'add'
      }
    },
    onClose() {
      this.data = {}
      this.visible = false
    },
    handleRemove(e, flag) {
      if (flag === 1) {
        this.fileList1 = []
      } else {
        this.fileList2 = []
      }
    },
    beforeUpload(file, flag) {
      if (flag === 1) {
        const isJpgOrPng = ['image/jpeg', 'image/png'].includes(file.type)
        if (!isJpgOrPng) {
          this.$notification['error']({
            message: '上传错误',
            description: '文件格式格式仅限于PNG,JPG',
          })
        }
        const isLt3M = file.size / 1024 / 1024 < 3
        if (!isLt3M) {
          this.$notification['error']({
            message: '上传错误',
            description: '文件大小不能超过3M',
          })
        }
        if (isJpgOrPng && isLt3M) {
          this.handleUpload(file, flag)
        }
      } else {
        this.handleUpload(file, flag)
      }
      return false
    },
    handleUpload(file, flag) {
      const formData = new FormData()
      formData.append('picture_byte', file)
      this.$message.info('上传中...')
      request.post('/picture/upload/', formData).then((res) => {
        if (flag === 1) {
          this.fileList1.push({
            uid: new Date().getTime(),
            name: 'image',
            status: 'done',
            url: res.img_url,
          })
        } else {
          this.fileList2.push({
            uid: new Date().getTime(),
            name: 'image',
            status: 'done',
            url: res.img_url,
          })
        }

        this.$message.success('上传成功')
      })
    },
    searchTypeRequest(name) {
      this.fetching = true
      getTypeList({ name: name, page: 1, page_size: 10 })
        .then((res) => {
          this.typeList = res.data
        })
        .finally(() => {
          this.fetching = false
        })
    },
    handleSearchType(value) {
      this.searchTypeRequest(value)
    },
    handleChange(value) {
      this.searchTypeRequest(value)
    },
    handleSubmit(e) {
      e.preventDefault()
      this.confirmLoading = true
      this.form.validateFields((err, values) => {
        if (!err) {
          if(this.fileList1.length < 1) {
            this.$message.error('请上传封面')
            return
          }
          if(this.fileList2.length < 1) {
            this.$message.error('请上传视频')
            return
          }
          let data = {
            name: values.name,
            remark: values.remark,
            poster_url: this.fileList1[0]?.url,
            video_url: this.fileList2[0]?.url,
            type: values.type,
          }
          if (this.mode === 'add') {
            addVideo(data)
              .then(() => {
                this.$message.success('新增成功')
                this.fileList = []
                this.form.resetFields()
                this.visible = false
                this.$emit('refresh')
              })
              .finally(() => {
                this.confirmLoading = false
              })
          } else {
            updateVideo(this.data.id, data)
              .then(() => {
                this.$message.success('修改成功')
                this.fileList = []
                this.form.resetFields()
                this.visible = false
                this.$emit('refresh')
              })
              .finally(() => {
                this.confirmLoading = false
              })
          }
        }
      })
    },
  },
}
</script>
